<?php
class DataBase
{
    private $dbLink;

    private function __construct()
    {
        $this->dbLink = NULL;
    }

    private function connect( $host, $user, $pass, $dbName )
    {
        $this->dbLink = mysqli_connect( $host, $user, $pass, $dbName );
        if ( $error = mysqli_connect_error() )
        {
            throw new Exception( 'Unable to connect!' );
        }
    }

    static function getInstance()
    {
        static $db = NULL;
        if ( !$db )
        {
            $db = new DataBase();
            $db->connect( DB_HOST, DB_USER, DB_PASS, DB_NAME );
        }
        return $db;
    }
    
    /**
     * The method returns $str with escaped special characters.
     * 
     * @param str   String.
     * 
     * @return  string.
     */
    public function quote( $str )
    {
        return mysqli_real_escape_string( $this->dbLink, $str );
    }
    
    private function selectResultToArray( $selectResult )
    {
        $resultArray = array();
        while ( $row = mysqli_fetch_assoc( $selectResult ) )
        {
            $resultArray[] = $row;
        }
        return $resultArray;
    }

    /**
     * The method sends a query to the database and returns the result.
     * Depending on the type of query response data varies.
     * 
     * @param query             The generated query in SQL.
     * @throw RuntimeException  If the request has caused an internal error
     *                          of the database server, an exception is thrown.
     * 
     * @return array, if the type of query - SELECT, or boolean, if another query type.
     */
    public function query( $query )
    {
        $explodeQuery = explode( ' ', $query ); 
        $typeOfQuery = strtoupper( $explodeQuery[0] );
        if ( $result = mysqli_query( $this->dbLink, $query ) )
        {
            if ( $typeOfQuery == 'SELECT' )
            {
                if ( $result )
                {
                    $resultArray = $this->selectResultToArray( $result );
                    return $resultArray;
                }
                return array();
            }
            return true;
        }
        else
        {
            throw new RuntimeException ( mysqli_error( $this->dbLink ) );
        }
    }
    
    /**
     * The method returns the last id inserted drains.
     * 
     * @return int.
     */
    public function getLastId()
    {
        return mysqli_insert_id( $this->dbLink );
    }
}
?>